const router = require('koa-router')();
const fs = require("fs")
const path = require("path")
const multer = require("koa-multer")
const ueditor = require('koa2-ueditor')
const send = require('koa-send')

const path_content = path.resolve(__dirname,"../../content.json")
const path_editor = path.resolve(__dirname,"../../editor")
const path_download = path.resolve(__dirname,"../../editor")

function writeFile(content){
  return new Promise((resolve, reject) => {
    fs.writeFile(path_content,JSON.stringify(content),"utf8",(err)=>{
      if(err){return resolve(false)}
      resolve(true)
    }) 
  });
}

router.post("/changeContent",async (ctx)=>{
  let params = ctx.request.body
  let content = params.content
  let err = await writeFile(content)
  if(!err){return ctx.body = {status:400}}
  ctx.body = {status:200}
})

router.post("/uploadPic",multer({ dest: 'upload/pic' }).single('pic'),async (ctx)=>{
  let file = ctx.req.file
  let path = file.destination + '/' + file.filename
  ctx.body = path
})

router.all("/upload/ueditor",ueditor(['upload', {
  "imageAllowFiles": [".png", ".jpg", ".jpeg"],
  "imagePathFormat": "/ueditor/{yyyy}{mm}{dd}/{filename}",  // 保存为原文件名
  "imageManagerListPath": "/ueditor/", //指定要列出图片的目录
  "imageManagerUrlPrefix": "/upload", //图片访问路径前缀
}]))

router.post("/build",async (ctx)=>{
  let params = ctx.request.body
  let content = params.content
  let err = await writeFile(content)
  if(!err){return ctx.body = {status:400}}
  let exec = require("child_process").exec
  let cmdStr01 = "npm run build-view"
  const build = () =>{
    return new Promise((resolve, reject) => {
        exec(cmdStr01,{cwd:path_editor},(err, stdout, stderr) => {
          console.log("err",err, "stdout",stdout, "stderr",stderr)
          resolve(err?false:true)
        })
    });
  }
  let errBuild = await build()
  if(!errBuild){return ctx.body = {status:400}}
  ctx.body = {status:200}
})

// router.get("/download",async (ctx)=>{
//   ctx.attachment("dist");
//   console.log(path_download)
//   await send(ctx,"dist",{root:path_download})
// })

module.exports = router